package com.uxsino.commons.logicSelector.propFunction;

import java.util.List;
import java.util.Map;

/**
 * This class get result in two stage, First get an object from an wrapped IPropValueFunction object
 * with possible type of Array, List or Map, 
 * then use indexString the retrieve the result.
 */
public class IndexedValueFunction implements IPropValueFunction {

    IPropValueFunction baseFunction;

    String indexString;

    public IndexedValueFunction(IPropValueFunction baseFunction, String index) {
        this.baseFunction = baseFunction;
        indexString = index;

    }

    @Override
    public Object get(Object object) {

        Object base = baseFunction.get(object);

        if (base == null) {
            return null;
        }

        if (base.getClass().isArray()) {
            return ((Object[]) base)[Integer.parseInt(indexString)];
        } else if (base instanceof List) {
            int i = Integer.parseInt(indexString);
            return ((List<?>) base).get(i);
        } else if (base instanceof Map) {
            return ((Map<?, ?>) base).get(indexString);
        }

        return null;

    }

}
